from flask import Flask, render_template, jsonify, request
from TicTacToe import TicTacToe

app = Flask(__name__)
game = TicTacToe()

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/make_move', methods=['POST'])
def make_move():
    data = request.get_json()
    row = data['row']
    col = data['col']
    
    # 玩家移动
    if not game.make_move((row, col), game.human):
        return jsonify({'error': '无效的移动'})
    
    # 检查玩家是否获胜
    winner = game.check_winner()
    if winner is not None:
        return jsonify({
            'board': game.board.tolist(),
            'game_over': True,
            'winner': winner
        })
    
    # AI移动
    ai_move = game.get_best_move()
    game.make_move(ai_move, game.ai)
    
    # 检查AI是否获胜
    winner = game.check_winner()
    
    return jsonify({
        'board': game.board.tolist(),
        'game_over': winner is not None,
        'winner': winner
    })

@app.route('/reset', methods=['POST'])
def reset():
    global game
    game = TicTacToe()
    return jsonify({'board': game.board.tolist()})

if __name__ == '__main__':
    app.run(debug=True)